package com.cslg.ac.demo.controller.auth.idcard;

import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.entity.user.User;
import com.cslg.ac.demo.service.auth.idCard.IdCardService;
import com.cslg.ac.demo.service.auth.mail.MailService;
import com.cslg.ac.demo.util.communicate.ResponseUtil;
import com.cslg.ac.demo.util.string.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@PropertySource(value = {"classpath:auth.properties"},encoding="utf-8")
public class IdcardController {
    @Autowired
    IdCardService idCardService;
    @Autowired
    MailService mailService;
    @Value("${idCardLength}")
    int idCardLength;
    @Value("${realnameLength}")
    int realnameLength;

    @RequestMapping(value = "/idCard/auth",method = RequestMethod.POST)
    public void authIdCard(@RequestParam String idCard,@RequestParam String name,HttpSession session,PrintWriter out){
        User user = (User) session.getAttribute("user");
        if(StringUtil.haveNullOrEmpty(idCard) || idCard.length() != idCardLength){
            ResponseUtil.responseCode(out,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        if(StringUtil.haveNullOrEmpty(name)|| StringUtil.lengthAbove(name,realnameLength)){
            ResponseUtil.responseCode(out,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        int code;
        try {
           code =  idCardService.auth(idCard,name,user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(out,ResponseCode.SERVER_ERROR);
            return;
        }
        ResponseUtil.responseCode(out,code);

    }

    /**
     * 是否已经验证身份
     * @param id
     * @param out
     */
    @RequestMapping(value = "/idCard/isAuth",method = RequestMethod.POST)
    public void isAuth(@RequestParam int id,PrintWriter out){
        int code;
        String name;
        try {
                name = idCardService.isAuth(id);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Map<String,Object> param = new HashMap<>();
        param.put("name",name);
        ResponseUtil.response(out,ResponseCode.REQUEST_SUCCESSED,param);
    }

}
